package com.hy.video.monitor.gb28181.transmit.event.request.impl;

import com.hy.video.monitor.conf.SipConfig;
import com.hy.video.monitor.gb28181.bean.Device;
import com.hy.video.monitor.gb28181.bean.VmcSipDate;
import com.hy.video.monitor.gb28181.transmit.SIPProcessorObserver;
import com.hy.video.monitor.gb28181.transmit.event.request.ISIPRequestProcessor;
import com.hy.video.monitor.gb28181.transmit.event.request.SIPRequestProcessorParent;
import com.hy.video.monitor.gb28181.auth.DigestServerAuthenticationHelper;
import com.hy.video.monitor.service.IDeviceService;
import com.hy.video.monitor.utils.DateUtil;
import gov.nist.javax.sip.RequestEventExt;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.header.Expires;
import gov.nist.javax.sip.header.SIPDateHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.header.*;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;

/**
 * SIP命令类型： REGISTER请求
 */
@Component
public class RegisterRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {

	private final Logger logger = LoggerFactory.getLogger(RegisterRequestProcessor.class);

	public final String method = "REGISTER";

	@Autowired
	private SipConfig sipConfig;

	@Autowired
	private SIPProcessorObserver sipProcessorObserver;

	@Autowired
	private IDeviceService deviceService;

	@Override
	public void afterPropertiesSet() throws Exception {
		// 添加消息处理的订阅
		// 添加消息处理的订阅
		// 添加消息处理的订阅
		// 将当前 ”REGISTER“ 事件处理句柄交给”观察者“ sipProcessorObserver
		sipProcessorObserver.addRequestProcessor(method, this);
	}

	/**
	 * SIP服务器需要验证SIP代理的身份才允许注册。
	 * 在SIP中使用已有的 HTTP 摘要（Digest）方式来认证。401 消息表示未认证
	 * ，它是SIP服务器对 aliceSIP代理的响应。同时，它在本端生成一个认证摘要（WWW-Authenticate），
	 * 一齐发送给SIP代理(SIP客户端)。
	 * <p>
	 * SIP代理 收到带有摘要的 401 后，后新发起注册请求，这一次，加上了根据收到的摘要和它自己的密码生成的认证信息（Authorization）。
	 * 并且CSeq 序号变成了 2
	 * <p>
	 * 设备请求注册命令来了。。。。
	 * <p>
	 * 设备注册流程
	 * 1：SIP代理向SIP服务器发送Register请求；
	 * 2：SIP服务器向SIP代理发送响应401，并在响应的消息头WWW_Authenticate字段中给出适合SIP代理的认证体制和参数；
	 * 3：SIP代理重新向SIP服务器发送Register请求，在请求的Authorization字段给出信任书，包含认证消息；
	 * 4：SIP服务器对请求进行验证，如果检查出SIP代理身份合法，向SIP代理发送成功响应 200 OK，如果身份不合法则发送拒绝服务应答。
	 */
	/**
	 * 收到注册请求 处理
	 *
	 * @param evt
	 */
	@Override
	public void process(RequestEvent evt) {
		try {
			RequestEventExt evtExt = (RequestEventExt) evt;
			String requestAddress = evtExt.getRemoteIpAddress() + ":" + evtExt.getRemotePort();
			logger.info("[注册请求] 开始处理: {}", requestAddress);
			Request request = evt.getRequest();
			ExpiresHeader expiresHeader = (ExpiresHeader) request.getHeader(Expires.NAME);
			Response response = null;
			boolean passwordCorrect = false;
			// 注册标志  0：未携带授权头或者密码错误  true：注册成功   false：注销成功
			// 注册标志
			boolean registerFlag = false;
			FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
			AddressImpl address = (AddressImpl) fromHeader.getAddress();
			SipUri uri = (SipUri) address.getURI();
			String deviceId = uri.getUser();

			AuthorizationHeader authHead = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
			// 未携带授权头或者密码错误 回复401
			if (authHead == null && !StringUtils.isEmpty(sipConfig.getPassword())) {
				logger.info("[注册请求] 未携带授权头 回复401: {}", requestAddress);
				response = getMessageFactory().createResponse(Response.UNAUTHORIZED, request);
				new DigestServerAuthenticationHelper().generateChallenge(getHeaderFactory(), response, sipConfig.getDomain());
				sendResponse(evt, response);
				return;
			}

			// 校验密码是否正确
			passwordCorrect = StringUtils.isEmpty(sipConfig.getPassword()) ||
					new DigestServerAuthenticationHelper().doAuthenticatePlainTextPassword(request, sipConfig.getPassword());

			if (!passwordCorrect) {
				// 注册失败
				response = getMessageFactory().createResponse(Response.FORBIDDEN, request);
				response.setReasonPhrase("wrong password");
				logger.info("[注册请求] 密码/SIP服务器ID错误, 回复403: {}", requestAddress);
				sendResponse(evt, response);
				return;
			}

			Device device = deviceService.queryDevice(deviceId);

			// 携带授权头并且密码正确
			response = getMessageFactory().createResponse(Response.OK, request);
			// 添加date头
			SIPDateHeader dateHeader = new SIPDateHeader();
			// 使用自己修改的
			VmcSipDate wvpSipDate = new VmcSipDate(Calendar.getInstance(Locale.ENGLISH).getTimeInMillis());
			dateHeader.setDate(wvpSipDate);
			response.addHeader(dateHeader);

			if (expiresHeader == null) {
				response = getMessageFactory().createResponse(Response.BAD_REQUEST, request);
				ServerTransaction serverTransaction = getServerTransaction(evt);
				serverTransaction.sendResponse(response);
				if (serverTransaction.getDialog() != null) {
					serverTransaction.getDialog().delete();
				}
				return;
			}
			// 添加Contact头
			response.addHeader(request.getHeader(ContactHeader.NAME));
			// 添加Expires头
			response.addHeader(request.getExpires());

			// 获取到通信地址等信息
			ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
			String received = viaHeader.getReceived();
			//SIP穿越NAT的rport机制（Via中的rport 和 received 参数）:shttps://blog.csdn.net/Rookie_Manito/article/details/112857889
			/**
			 * RPORT机制： 客户端需要在top most via上带上rport参数
			 *   1、服务端发现via中有rport参数时，将此via中加入received参数和rport参数，参数带的值分别是服务端看到
			 *   的消息来源地址和端口（如果有NAT等地址转换设备，则即为转换后的IP和port）。
			 *   2、当有需要发送的响应时，按照rport中的端口发送SIP 响应。也就是说IP和端口均完全遵照从哪里来的，发回哪里去的原则。
			 *   （如果没有rport字段时，服务端的策略是IP使用UDP包中的地址，即从哪里来回哪里去，但是端口使用的via中的端口）
			 *  RFC文档中的例子：
			 *  客户端发送INVITE形如：
			 *      INVITE sip:user@example.com SIP/2.0
			 *      Via: SIP/2.0/UDP 10.1.1.1:4540;rport;branch=z9hG4bKkjshdyff
			 *
			 *  服务端收到后根据自己所得到的源地址和端口，重写via,如有必要添加自己的via转发
			 *      INVITE sip:user@example.com SIP/2.0
			 *      Via: SIP/2.0/UDP proxy.example.com;branch=z9hG4bKkjsh77
			 *      Via: SIP/2.0/UDP 10.1.1.1:4540;received=192.0.2.1;rport=9988;branch=z9hG4bKkjshdyff
			 *
			 *  当需要给此请求发送响应时，发往received,rport两个参数记录的IP和PORT。NAT设备再把发往转换后地址192.0.2.1的包发往10.1.1.1地址。
			 *      SIP/2.0 200 OK
			 *      Via: SIP/2.0/UDP 10.1.1.1:4540;received=192.0.2.1;rport=9988;branch=z9hG4bKkjshdyff
			 */
			int rPort = viaHeader.getRPort();
			// 解析本地地址替代
			if (StringUtils.isEmpty(received) || rPort == -1) {
				received = viaHeader.getHost();
				rPort = viaHeader.getPort();
			}
			if (device == null) {
				device = new Device();
				device.setStreamMode("UDP");
				device.setCharset("GB2312");
				device.setGeoCoordSys("WGS84");
				device.setDeviceId(deviceId);
			}
			device.setIp(received);
			device.setPort(rPort);
			device.setHostAddress(received.concat(":").concat(String.valueOf(rPort)));
			if (expiresHeader.getExpires() == 0) {
				// 注销成功
				registerFlag = false;
			} else {
				// 注册成功
				device.setExpires(expiresHeader.getExpires());
				registerFlag = true;
				// 判断TCP还是UDP
				ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
				String transport = reqViaHeader.getTransport();
				device.setTransport("TCP".equals(transport) ? "TCP" : "UDP");
			}

			sendResponse(evt, response);
			// 注册成功
			// 保存到redis
			if (registerFlag) {
				logger.info("[注册成功] deviceId: {}->{}",  deviceId, requestAddress);
				device.setRegisterTime(DateUtil.getNow());
				deviceService.online(device);
			} else {
				logger.info("[注销成功] deviceId: {}->{}" ,deviceId, requestAddress);
				deviceService.offline(deviceId);
			}
		} catch (SipException | InvalidArgumentException | NoSuchAlgorithmException | ParseException e) {
			e.printStackTrace();
		}

	}

	private void sendResponse(RequestEvent evt, Response response) throws InvalidArgumentException, SipException {
		ServerTransaction serverTransaction = getServerTransaction(evt);
		if (serverTransaction == null) {
			logger.warn("[回复失败]：{}", response);
			return;
		}
		serverTransaction.sendResponse(response);
		if (serverTransaction.getDialog() != null) {
			serverTransaction.getDialog().delete();
		}
	}

}

